<?php
class PartnerCat extends CActiveRecord {

    public $catId;
    public $name;
    public $about;
    public $title;
    public $keywords;
    public $parentId = 0;
    public $redactor1 = 0.95;
    public $redactor2 = 1;
    public $redactor3 = 1.05;
    public $reviewRules;
    public $reviewRating1;
    public $reviewRating2;
    public $reviewRating3;
    public $reviewRating4;
    public $revRat1About;
    public $revRat2About;
    public $revRat3About;
    public $revRat4About;
    public $ratingRules;
    
    public $inputTitle;
    public $radioBut;
    public $reviewRatingAd;
    
    private $oldParent;

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return 'partners_cat';
    }
    
    public function attributeLabels() {
        return array(
            'name' => 'Название категории',
            'about' => 'Описание',
            'title' => 'Тег title',
            'keywords' => 'Тег keywords',
            'redactor1' => 'Оценка редактора 1 ур',
            'redactor2' => 'Оценка редактора 2 ур',
            'redactor3' => 'Оценка редактора 3 ур',
            'reviewRules' => 'Правила на отзыв',
            'ratingRules' => 'Подсказка с описанием параметров',
            'parentId' => 'Родительская категория',
            'reviewRating1' => '1 оценка для отзыва',
            'reviewRating2' => '2 оценка для отзыва',
            'reviewRating3' => '3 оценка для отзыва',
            'reviewRating4' => '4 оценка для отзыва',
            'revRat1About' => 'Описание 1 оценки отзыва',
            'revRat2About' => 'Описание 2 оценки отзыва',
            'revRat3About' => 'Описание 3 оценки отзыва',
            'revRat4About' => 'Описание 4 оценки отзыва',
        );
    }
    
    public function relations() {
        return array(
            'parent'=>array(self::BELONGS_TO, 'PartnerCat', 'parentId'),
            'subcat'=>array(self::HAS_MANY, 'PartnerCat', array('catId'=>'parentId')),
            'ratings'=>array(self::HAS_MANY, 'PartnerCatRaiting', 'catId'),
            'relPartners'=>array(self::HAS_MANY, 'Partner', 'catId'),
            'score'=>array(self::HAS_ONE, 'PartnersCatScore', 'catId'),
        );
    }
    
    public function rules() {
        return array(
            array('name, redactor1, redactor2, redactor3', 'required', 'message'=>'{attribute} не может быть пустым'),
            array('keywords, title, reviewRatingAd, about, reviewRules, inputTitle, radioBut, parentId, ratingRules, revRat1About, revRat2About, revRat3About, revRat4About', 'safe'),
            array('reviewRating1, reviewRating2, reviewRating3, reviewRating4', 'reviewRatingValidator'),
        );
    }
    
    public function reviewRatingValidator($attribute,$params) {
        if(!$this->parentId && empty($this->$attribute)) 
                $this->addError ($attribute, "$attribute не может быть пустым");
    }
    
    public function afterFind() {
        $this->oldParent = $this->parentId;
    }
    
    public function afterSave() {
        CacheTaggedHelper::deleteByTags($this->tableName());
        if(!empty($this->inputTitle)) {
            if($this->getScenario() == 'update') {
                $ratingData = PartnerCatRaiting::model()->findAll("catId=$this->primaryKey");
                
                foreach ($this->inputTitle as $k=>$v) {
                                        
                    if(!isset($this->radioBut[$k]) || !isset($this->inputTitle[$k])) continue;
                    
                    if(strpos($k, 'id') !== false) {
                        $id = preg_replace("/\D/", '', $k);
                        PartnerCatRaiting::model()->updateByPk($id, array('type'=>end($this->radioBut[$k]), 'val'=>end($v)));
                        $insertArr[$id] = 1;
                    } else {
                        Yii::app()->db->createCommand()->insert('partners_catraitings', array(
                            'catId'=>$this->catId, 'type'=>end($this->radioBut[$k]), 'val'=>end($v)
                        ));
                    }
                }
                
                foreach ($ratingData as $item) {
                    if(isset($insertArr[$item->catRatingId])) continue;
                    PartnerCatRaiting::model()->deleteByPk($item->catRatingId);
                }
            } else {
                PartnerCatRaiting::model()->deleteAll("catId=$this->primaryKey");
                foreach ($this->inputTitle as $k=>$v) {
                    if(!$this->radioBut[$k] || !end($this->inputTitle[$k])) continue;
                    Yii::app()->db->createCommand()->insert('partners_catraitings', array(
                        'catId'=>$this->catId, 'type'=>end($this->radioBut[$k]), 'val'=>end($v)
                    ));
                }
            }
        } else {
            PartnerCatRaiting::model()->deleteAll("catId=$this->primaryKey");
        }   
        
        Yii::app()->db->createCommand()->delete('partners_ad_rev_rat', 'catId=:id', array(':id'=>$this->primaryKey));
        if(!$this->parentId) {
            for($i=0; $i<count($this->reviewRatingAd['val']); $i++) {
                if(!empty($this->reviewRatingAd['val'][$i])) {
                    Yii::app()->db->createCommand()->insert('partners_ad_rev_rat', array(
                        'catId'=>$this->primaryKey, 'val'=>$this->reviewRatingAd['val'][$i], 'about'=>$this->reviewRatingAd['about'][$i]));
                }    
            }
        }
    }
    
    public function beforeSave() {
        if(!parent::beforeSave()) return false;
        
        if($this->parentId) {
            #if(!$this->oldParent) PartnerCat::model()->updateAll(array('parentId'=>'0'), array('parentId'=>$this->primaryKey));
            
            $parent = PartnerCat::model()->findByPk($this->parentId, array('select'=>'title, keywords, reviewRules, reviewRating1, reviewRating2, reviewRating3, reviewRating4'));
            if(empty($this->title)) $this->title = $parent->title;
            if(empty($this->keywords)) $this->keywords = $parent->keywords;
            
            $this->reviewRules = $parent->reviewRules;
            $this->reviewRating1 = $parent->reviewRating1;
            $this->reviewRating2 = $parent->reviewRating2;
            $this->reviewRating3 = $parent->reviewRating3;
            $this->reviewRating4 = $parent->reviewRating4;
        }
        if(empty($this->title))
        {
         $this->title=$this->name." отзывы";  
        }
        return true;
    }
    
    protected function afterDelete() {
        CacheTaggedHelper::deleteByTags($this->tableName());
    }
        
    public function beforeDelete() {
        if(!parent::beforeDelete()) return false;
        PartnerCat::model()->deleteAllByAttributes(array('parentId'=>$this->primaryKey));
        Partner::model()->deleteAllByAttributes(array('catId'=>$this->primaryKey));
        Yii::app()->db->createCommand()->delete('partners_catraitings', 'catId=:id', array(':id'=>$this->primaryKey));
        
        return true;
    }
}
